package cn.daniellee.plugin.el.listener;

import cn.daniellee.plugin.el.EnterLimiter;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.event.player.PlayerQuitEvent;

public class PlayerListener implements Listener {

	@EventHandler
	public void onPlayerLogin(PlayerLoginEvent e) {
		if (EnterLimiter.getInstance().isLimited()) {
			if (e.getPlayer().hasPermission("enterlimiter.bypass")) return;
			// 进入时检查是否有时长，不然拒绝
			Integer available = EnterLimiter.availableSecond.get(e.getPlayer().getName());
			if (available == null) {
				// 如果服务器当前没人，则可能漏了消息，附送5秒时间用于接收消息
				if (Bukkit.getOnlinePlayers().isEmpty()) {
					EnterLimiter.availableSecond.put(e.getPlayer().getName(), 5);
				} else {
					e.disallow(PlayerLoginEvent.Result.KICK_WHITELIST, EnterLimiter.getInstance().getConfig().getString("message.buy-first", "&ePlease purchase time first.").replace("&", "§"));
				}
			}
		}
	}

	@EventHandler
	public void onPlayerQuit(PlayerQuitEvent e) {
		if (EnterLimiter.getInstance().isLimited()) {
			// 退出时也保存一次时长
			Integer available = EnterLimiter.availableSecond.get(e.getPlayer().getName());
			if (available != null) {
				EnterLimiter.getInstance().getPlayerData().set(e.getPlayer().getName() + ".available", available);
				EnterLimiter.getInstance().savePlayerData();
			}
		}
	}

}
